package com.yangleping.dynamic.thread.pool.sdk.trigger.job;

import com.alibaba.fastjson.JSON;
import com.yangleping.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import com.yangleping.dynamic.thread.pool.sdk.domain.model.ThreadPoolConfigEntity;
import com.yangleping.dynamic.thread.pool.sdk.registry.IRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 线程池数据上报任务
 */
public class ThreadPoolDataReportJob {

    private Logger logger = LoggerFactory.getLogger(ThreadPoolDataReportJob.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolDataReportJob(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    // 按照定时任务配置，每隔20秒执行一次线程池信息上报
    @Scheduled(cron = "0/20 * * * * ?")
    public void execReportThreadPoolList() {
        // 查询当前所有的线程池配置信息
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolList();
        // 上报所有线程池的配置信息到监控中心
        registry.reportThreadPool(threadPoolConfigEntities);
        // 记录日志，方便追踪和审计
        logger.info("动态线程池，主动上报线程池信息：{}", JSON.toJSONString(threadPoolConfigEntities));

        // 遍历每个线程池配置，单独上报其详细配置参数
        for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigEntities) {
            // 上报单个线程池的详细配置参数到监控中心
            registry.reportThreadPoolConfigParameter(threadPoolConfigEntity);
            // 记录日志，方便追踪和审计
            logger.info("动态线程池，主动上报线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));
        }
    }
}
